#!/usr/bin/env python
# encoding: utf-8
'''
@author: toby
@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.
@contact: hejunwang01@126.com
@software: pycharm
@file: app.py
@time: 2021-03-25 23:21
@desc:
'''

from flask import Flask,render_template,request,jsonify,send_file,make_response
from celery_task.tasks import *
from flask_cors import CORS
from flask_cors import cross_origin
from utils import mysubprocess
from utils.operadirectory import last_file
import os
import logging
from utils.hashmd5 import MD5
from utils.operadirectory import as_dict

from apps.user import bp as user_bp
from apps.works import bp as works_bp
from apps.myspider import bp as myspider_bp
from apps.project_list import bp as pro_bp

from utils.writetoexcel import OperaExcel
from flask_migrate import  Migrate
from models import OverView

from dbs import db
ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'xls', 'JPG', 'PNG', 'xlsx', 'gif', 'GIF','pdf'])
DOWNLOADPATH ="/root/flask-celery-hjw/flask-celery/pytest_pkg"
FILEUPPATH ="/root/flask-celery-hjw/flask-celery/pytest_pkg/testcase-data/"
ELEMENTFIND ="/root/flask-celery-hjw/flask-celery/"


logger = logging.getLogger(__name__)
# 静态文件的配置
app = Flask(__name__,
            static_folder='./dist',
            template_folder='./dist/templates',
            static_url_path='')
# 导入配置文件采用：
app.config.from_object('settings.TestingConfig')
# 把app绑定到db上
db.init_app(app)
# 注册蓝图 ,有条理的把app对应的方法给分开 ,如果想要增加其他的,在apps中增加类似users就可以了
app.register_blueprint(user_bp)
app.register_blueprint(works_bp)
app.register_blueprint(myspider_bp)
app.register_blueprint(pro_bp)

# 创建一个migrate对象,处理数据库迁移的问题
migrate = Migrate(app,db)

# Flask项目中app与model拆分 参考  https://www.jianshu.com/p/505449668d38
CORS(app)    # 解决flask 跨域问题

# 路由 index
@app.route('/',methods=['GET'])
def index():
    # db.create_all()
    return render_template('index.html',name="index")

# 数据库查询
@app.route('/v1/select',methods=['GET'])
def sql_select():
    print('select print')
    sql_task = mysql_select.apply_async()
    return jsonify({'action':'select',"task_id":sql_task.id,"code":200})


# 数据统计查询
@app.route('/v1/census',methods=['GET'])
def censusdata():
    result = OverView.query.all()
    data_list = []
    for item in result:
        data_list.append(as_dict(item))

    return jsonify({"code":200,"datalist":data_list})


@app.route('/v1/subproc',methods=['POST'])
def run_command():
    if request.method =="POST":
        try:
            cmdline = request.json.get("inputstr")
            print(cmdline)
            res = mysubprocess.runcmd(cmdline)
            return jsonify({'code': 200,'msg':res})
        except Exception as e:

            return jsonify({'code': 400, 'msg':str(e) })
    else:
        return jsonify({'code':400,'msg':"request method fail"})

# 判断文件的后缀
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

# 测试报告下载
@app.route('/v1/api/download', methods=['GET'])
def file_download():
    filepath = os.path.join(DOWNLOADPATH,'reports/')
    print('filepath-->{}'.format(filepath))
    pd =last_file(filepath)
    print("路径:{},\n 文件名称:{}".format(pd[0],pd[1]))
    if pd[1]:
        # attachment_filename="down.txt", as_attachment=True 附件
        return send_file(filepath + pd[1], as_attachment=True)
    else:
        return jsonify({'code':-1,'msg':'文件不存在'})


@app.route('/download2', methods=['GET'])
def download():
    file = open("./upload/test.zip", "rb").read()
    response = make_response(file)
    return response

# 上传文件
@app.route('/v1/api/upload',methods=['post'])
def api_upload():
    if request.method =='POST':
        files = request.files.get('files')
        print('files:-->',files.filename)
        # os.path.join拼接地址，上传地址，f.filename获取文件名
        if os.path.exists(os.path.join(FILEUPPATH,files.filename)):
            return jsonify({'code':300,'msg':u'重复文件名,请重新提交'})
        else:
            files.save(os.path.join(FILEUPPATH, files.filename))
            return jsonify({'code':200,'msg':u'上传成功'})
    else:
        return  jsonify({'code':500,'msg':u'请使用正确的请求方式'})

@app.route("/v1/addelement.json",methods=['POST'])
def addelement():
    if request.method =='POST':
        t1 = request.json.get('type1')
        elementpath1 = request.json.get('elementpath1')

        if t1 and elementpath1 :
            data = dict({(t1,elementpath1)})
            print(data)
            op = OperaExcel(ELEMENTFIND+"pom_framwork/element-data/uielement.xlsx")
            op.inset_row(data=data)
            return jsonify({"code": 200, 'msge':"ok" })
    else:

        return jsonify({"code":-1,'msge':u'请使用正确的请求方式'})




@app.route("/v1/writeconf.json",methods=['POST'])
def writeconfig():
    if request.method=="POST":
        name = request.json.get('name')
        passwd = request.json.get('passwd')
        environment = request.json.get('environment')
        script = request.json.get('script')

        print(name,passwd,environment,script)
        config = configparser.ConfigParser()
        # 读取文件
        config.read(os.getcwd()+'/pytest_pkg/param1.ini')
        print(os.getcwd()+'/pytest_pkg/param1.ini')
        # set
        section_name = 'apiconfig'
        # config.add_section(section_name)
        config.set(section_name, 'name', name)
        config.set(section_name, 'passwd', MD5().set_md5(passwd))
        config.set(section_name, 'environment', environment)
        config.set(section_name, 'script', script)

        config.set(section_name, 'loginurl', "/jweb_management/systemUser/login.json")
        config.set(section_name, 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36')

         # 当前文件的路径
        filepath = os.getcwd()+'/pytest_pkg/param1.ini'

        config.write(open(filepath, 'r+',encoding="utf-8"))
        return jsonify({"code": 200, 'msg':"写入完成!" })
    else:
        return jsonify({"code":-1,'msge':'请使用正确的请求方式'})






if __name__ == '__main__':
    print('url Rule地址 ：-------------------\n')
    print(app.url_map)
    print('url Rule地址 ：-------------------\n')
    app.run(host='0.0.0.0')

